package de.traveltainment.concept.envers.api;

import de.traveltainment.concept.envers.audit.lifecycle.Lifecycle;
import de.traveltainment.concept.envers.audit.lifecycle.Stage;
import de.traveltainment.concept.envers.entities.Vito;
import de.traveltainment.concept.envers.repository.LifecycleRepositoy;
import de.traveltainment.concept.envers.repository.UploadRepository;
import de.traveltainment.concept.envers.repository.VitoRepository;
import org.hibernate.envers.AuditReader;
import org.hibernate.envers.AuditReaderFactory;

import javax.enterprise.context.RequestScoped;
import javax.inject.Inject;
import javax.persistence.EntityManager;

/**
 * Created by borlis on 17.06.2014.
 */
@RequestScoped
public class LifecycleManager {

    @Inject
    private LifecycleRepositoy lifecycleRepositoy;

    @Inject
    private UploadRepository uploadRepository;

    @Inject
    private VitoRepository vitoRepository;

    @Inject
    private EntityManager em;

    @Inject
    private UploadManager uploadManager;


    public void revert(Vito vito, Stage stage, Boolean uploadLater) {
        Vito versioned = identify(vito, stage);
        vitoRepository.merge(versioned);
        if (uploadLater) {
            uploadManager.uploadConfiguration(vito);
        }
    }

    private Vito identify(Vito vito, Stage stage) {
        AuditReader reader = AuditReaderFactory.get(em);
        return reader.find(Vito.class, vito.getId(), getRevision(vito, stage));
    }

    private Integer getRevision(Vito vito, Stage stage) {
        Lifecycle lifecycle = lifecycleRepositoy.findWithStage(vito.getId(), stage);
        return lifecycle.getRevId();
    }
}
